package com.dormms.www.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @Title: CorsConfig
 * @Author Tanght 363993584@qq.com
 * @Date 2024/7/24 17:17
 * @description:
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter(){

        CorsConfiguration conf = new CorsConfiguration();
        //允许哪些请求源跨域访问,比如:http://localhost:8080.如果允许所有请求源跨域访问,可以使用"*"通配符
        conf.addAllowedOriginPattern("*");
        //允许所有的请求头跨域访问
        conf.addAllowedHeader("*");
        //允许所有的请求方式跨域访问
        conf.addAllowedMethod("*");
        //允许前端请求携带认证信息,如果前端打开了allowCredentials,则后端服务也必须打开
        conf.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",conf);
        return new CorsFilter(source);
    }
}
